package com.example.calculator.service.impl;

import com.example.calculator.model.CalculationRequest;
import com.example.calculator.model.CalculationResponse;
import com.example.calculator.service.CalculatorService;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

@Service
public class CalculatorServiceImpl implements CalculatorService {
    @Override
    public CalculationResponse calculate(CalculationRequest request) {
        CalculationResponse response = new CalculationResponse();
        try {
            // 使用 JavaScript 引擎来计算表达式
            ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
            Object result = engine.eval(request.getExpression());
           // double result = evaluateExpression(request.getExpression());
            response.setResult(result.toString());
        } catch (Exception e) {
            response.setResult(Double.NaN+"");
        }
        return response;
    }

    private double evaluateExpression(String expression) {
        // 使用 ScriptEngine 或其他方法解析表达式
        // 这里简化为直接计算
        return Double.parseDouble(expression);
    }
}